package com.xiezc.action;

import com.xiaoleilu.hutool.lang.Assert;
import com.xiezc.dto.RespData;
import com.xiezc.entity.User;
import com.xiezc.util.TBPanException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
import com.xiezc.util.RetrofitUtil;

import java.io.IOException;


/**
 * Created by wb-xzc291800 on 2017/6/22.
 */
@Component
@Slf4j
public class LoginAction {

    LoginInterface loginInterface = RetrofitUtil.create(LoginInterface.class);

    /**
     * 登录
     *
     * @param user
     * @return
     * @throws java.io.IOException
     */
    public RespData login(User user) {

        Assert.notNull(user);
        Assert.notBlank(user.getUserName());
        Assert.notBlank(user.getPassword());

        Call<RespData> respDataCall = loginInterface.login(user);
        try {
            return respDataCall.execute().body();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new TBPanException(e);
        }
    }




    /**
     * 退出
     *
     * @param ticket
     * @return
     * @throws java.io.IOException
     */
    public RespData logout(String ticket) throws IOException {
        Assert.notBlank(ticket);
        Call<RespData> respDataCall = loginInterface.logout(ticket);
        return respDataCall.execute().body();
    }

    /**
     * 注册
     *
     * @param user
     * @return
     * @throws java.io.IOException
     */
    public RespData register(User user) throws IOException {
        Assert.notNull(user);
        Assert.notBlank(user.getUserName());
        Assert.notBlank(user.getPassword());

        Call<RespData> respDataCall = loginInterface.register(user);
        return respDataCall.execute().body();
    }

    /**
     * 内部请求的接口
     */
    public interface LoginInterface {
        @POST("login")
        Call<RespData> login(@Body User user);

        @POST("logout")
        Call<RespData> logout(String ticket);

        @POST("register")
        Call<RespData> register(@Body User user);
    }
}

